import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 50000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 判断token是否存在
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  async error => {
    console.dir(error)
    // 处理token失效
    if (error.response.status === 401) {
      console.log(123)
      router.push('/login')
      Message.error('登录信息已过期，请重新登录')
      store.commit('user/delToken')
      return Promise.reject(error)
    }

    return Promise.reject(error)
  }
)

export default service
